package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimeLineService timeLineService;

    //发布动态
    @Override
    public String publish(Movement movement) {
        try {
            //保存动态详情
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
//            //查询当前用户的好友数据
//            Criteria criteria=Criteria.where("userId").is(movement.getUserId());
//            Query query=Query.query(criteria);
//            List<Friend> friends=mongoTemplate.find(query, Friend.class);
//            //循环好友数据，构建时间线数据存入数据库
//            for (Friend friend : friends) {
//                MovementTimeLine timeLine=new MovementTimeLine();
//                timeLine.setMovementId(movement.getId());
//                timeLine.setUserId(friend.getUserId());
//                timeLine.setFriendId(friend.getFriendId());
//                timeLine.setCreated(System.currentTimeMillis());
//                mongoTemplate.save(timeLine);
//            }
                timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();

    }

    //查询个人动态
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0l,movements);
    }

    //查询好友动态
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //1、查询好友时间线表
        Query query = Query.query(Criteria.where("friendId").is(friendId))
                .skip((page - 1)*pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> lines = mongoTemplate.find(query, MovementTimeLine.class);
        //2、提取动态id集合
        List<ObjectId> movementIds = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);
        //TODO-------------好友动态出现bug------------------
        if(movementIds == null){
           return randomMovements(pagesize);
        }
        //3、根据动态id查询动态详情
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds).and("state").is(1));
        return mongoTemplate.find(movementQuery, Movement.class);
    }

    /**
     * 随机查询推荐动态数据
     * @param counts
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象，设置统计参数
        TypedAggregation aggregation= Aggregation.newAggregation(Movement.class,Aggregation.sample(counts));
        //调用mongoTemplate方法去统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //获取统计结果
        return results.getMappedResults();
    }

    /**
     * 按照pid数组查询推荐动态
     * @param pids
     * @return
     */
    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query=Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * 查询单条动态
     * @param movementId
     * @return
     */
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId, Movement.class);
    }

    /**
     * 根据id查询动态列表
     * @param uid
     * @param state
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query=new Query();
        if(uid !=null){
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if(state != null){
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);
        query.with(Sort.by(Sort.Order.desc("created"))).limit(pagesize).skip((page-1)*pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,list);
    }

    //更新动态状态
    @Override
    public void update(String movementId, Integer state) {
        Query query = Query.query(Criteria.where("id").is(movementId));//todo 报错？老师这么写：new ObjcetId(movementId)
        Update update = Update.update("state", state);
        mongoTemplate.updateFirst(query,update,Movement.class);
    }

}
